from pygame import SurfaceType

from util import Logger as log
import pygame.transform as pt
import pygame
import os, json


class Texture:
    pass


class TextureA(Texture):
    def __init__(self, x: int, y: int, width: int, height: int):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.scale = 1
        self.rect = {self.scale: pygame.Rect(x * self.scale, y * self.scale, width * self.scale, height * self.scale)}

    def get_rect(self, scale=-1):
        if scale == -1:
            scale = self.scale
        self.set_scale(scale)
        return self.rect[scale]

    def set_scale(self, scale: int):
        if not scale in self.rect:
            self.scale = scale
            self.rect[scale] = pygame.Rect(self.x * scale, self.y * scale, self.width * scale, self.height * scale)


class TextureGifs(Texture):
    width, height = 0, 0

    def __init__(self, textures: list[str], interval: int):
        self.textures = textures
        self.interval = interval


class Image:
    def __init__(self, image_data: SurfaceType):
        self.image_data = image_data
        scale = 1
        w, h = image_data.get_size()
        self.image = {scale: pt.scale(image_data, (w * scale, h * scale))}

    def get_image(self, scale: int):
        self.set_scale(scale)
        return self.image[scale]

    def set_scale(self, scale: int):
        if not scale in self.image:
            w, h = self.image_data.get_size()
            self.image[scale] = pt.scale(self.image_data, (w * scale, h * scale))


textures = {}


def read_resources():
    global textures
    base_dir = './resources/textures'
    files = [os.path.join(base_dir, file) for file in os.listdir(base_dir)]
    for file in files:
        key = os.path.splitext(os.path.basename(file))[0]
        if file.endswith(".json"):
            log.info(f"read resources -> {file}")
            with open(file, "r", encoding="UTF-8") as f:
                json_dict = json.load(f)

            if not key in textures:
                textures[key] = {}

            for data in json_dict["data"]:
                log.info(f"read {file} -> name: {data["name"]} | type: {data["type"]}")
                if data["type"] == "texture":
                    textures[key][data["name"]] = TextureA(data["x"], data["y"],
                                                           data["width"], data["height"])

                elif data["type"] == "gifs":
                    textures[key][data["name"]] = TextureGifs(data["textures"], data["interval"])
                    if "width" in data:
                        textures[key][data["name"]].width = data["width"]
                    if "height" in data:
                        textures[key][data["name"]].height = data["height"]

        elif file.endswith(".png"):
            log.info(f"read {file} -> is image")
            if not key in textures:
                textures[key] = {}

            textures[key]["image"] = Image(pygame.image.load(file).convert_alpha())


def init():
    log.info("ResourceManager -> init")
    log.info("ResourceManager -> read resources")
    read_resources()
